import {
	createRouter,
	createWebHashHistory
} from "vue-router";
import {
	showConfirmDialog
} from 'vant';
import {
	getTokenLocal
} from "@/utils/auth.js"; // 假设从这个文件获取token，需根据实际情况调整
// 每个路由都需要映射到一个组件。
const routes = [{
		path: "/",
		redirect: "/home",
		meta: {
			title: "首页"
		}
	},
	{
		path: "/home",
		component: () => import("@/views/home/Home.vue"),
		name: "home",
		meta: {
			title: "首页"
		}
	},
	{
		path: '/newsList',
		component: () => import('@/views/news/NewsList.vue'),
		name: "newsList",
		meta: {
			title: "新闻资讯列表"
		}
	},
	{
		path: '/news/:id',
		component: () => import('@/views/news/NewsDetail.vue'),
		name: "newsDetail",
		meta: {
			title: "新闻资讯详情"
		}
	},
	{
		path: '/imageShare',
		component: () => import('@/views/ImageShare.vue'),
		name: 'imageShare',
		meta: {
			title: "图片分享"
		}
	},
	{
		path: '/feedback',
		component: () => import('@/views/Feedback.vue'),
		name: 'feedback',
		meta: {
			title: "留言反馈"
		}
	},
	{
		path: '/contact-us',
		component: () => import('@/views/ContactUs.vue'),
		name: 'contact-us',
		meta: {
			title: "联系我们"
		}
	},
	{
		path: "/productList", // 统一命名规范
		component: () => import('@/views/product/Productlist.vue'),
		name: "productList",
		meta: {
			title: "商品"
		}
	},
	{
		path: "/productDetail/:id",
		name: "productDetail",
		component: () => import('@/views/product/ProductDetail.vue'),
		meta: {
			title: "商品详情"
		}
	},
	{
		path: "/shopcart",
		component: () => import("@/views/shopcart/Shopcart.vue"),
		name: "shopcart",
		meta: {
			title: "购物车",
			requireAuth: true // 需要Token
		}
	},
	{
	        path: "/message",
	        component: () => import("@/views/message/MessageList.vue"),
	        name: "message",
	        meta: {
	            title: "消息"
	        }
	    },
	{
		path: "/chatPage",
		component: () => import("@/views/message/chatPage.vue"),
		name: "chatPage",
		meta: {
			title: "聊天"
		}
	},
	{
		path: "/user",
		component: () => import("@/views/user/User.vue"),
		name: "user",
		meta: {
			title: "我的"
		}
	},
	{
		path: "/login",
		component: () => import("@/views/user/Login.vue"),
		name: "login",
		meta: {
			title: "登录"
		}
	},
	{
		path: "/register",
		component: () => import("@/views/user/Register.vue"),
		name: "register",
		meta: {
			title: "用户注册"
		}
	},
	{
		path: "/user/profile",
		component: () => import("@/views/user/Profile.vue"),
		name: "profile",
		meta: {
			title: "个人资料"
		}
	},
	{
		path: "/user/updatePwd",
		component: () => import("@/views/user/UpdatePwd.vue"),
		name: "updatePwd",
		meta: {
			title: "修改密码"
		}
	},
	{
		path: "/order/create",
		component: () => import("@/views/order/OrderCreate.vue"),
		name: "orderCreate",
		meta: {
			title: "新建订单"
		}
	},
	{
		path: "/user/addressList",
		component: () => import("@/views/address/AddressList.vue"),
		name: "addressList",
		meta: {
			title: "收货地址列表",
			requireAuth: true
		}
	},
	{
		path: "/user/addressEdit/:id",
		component: () => import("@/views/address/AddressEdit.vue"),
		props: true,
		name: "addressEdit",
		meta: {
			title: "收货地址",
			requireAuth: true
		}
	},
	{
		path: "/order/list",
		component: () => import("@/views/order/OrderList.vue"),
		name: "orderList",
		meta: {
			title: "我的订单",
			requireAuth: true
		}
	},
	{
		path: "/order/detail/:id",
		component: () => import("@/views/order/OrderDetail.vue"),
		props: true,
		name: "orderDetail",
		meta: {
			title: "订单详情", // 修正标题
			requireAuth: true
		}
	},
	{
		path: "/myFavorites",
		component: () => import("@/views/MyFavorites.vue"),
		props: true,
		name: "myFavorites",
		meta: {
			title: "我的收藏", // 修正标题
			requireAuth: true
		}
	},
	{
		path: "/:pathMatch(.*)",
		name: "notFound",
		component: () => import('@/views/NotFound.vue'),
		meta: {
			title: "导航页面不存在"
		}
	},
	
];

// 创建路由实例并传递 `routes` 配置
const router = createRouter({
	// 我们在这里使用 hash 模式。
	history: createWebHashHistory(),
	routes // `routes: routes` 的缩写
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
	if (to.meta.title) {
		document.title = to.meta.title;
	}

	if (to.name === 'login') {
		console.log(`${from.name}跳转到login`);
		next();
		return;
	}

	if (!to.meta.requireAuth) {
		console.log(`${from.name}跳转到${to.name},目的路由不需要用户认证`);
		next();
		return;
	}

	try {
		const token = getTokenLocal();
		if (!token) {
			console.log(`${from.name}跳转到${to.name},目的路由需要用户认证，Token不存在！强制跳转到login`);
			showConfirmDialog({
				message: "没有Token,需要重新登录吗?"
			}).then(() => {
				next({
					name: 'login',
					query: {
						redirect: to.path
					}
				});
			}).catch(() => {
				router.push({
					name: "home"
				});
			});
			return;
		}
		console.log(`${from.name}跳转到${to.name},目的路由需要用户认证，Token也存在！`);
		next();
	} catch (error) {
		console.error('获取token时出错:', error);
		showConfirmDialog({
			message: "获取用户认证信息出错，请重新登录！"
		}).then(() => {
			next({
				name: 'login',
				query: {
					redirect: to.path
				}
			});
		}).catch(() => {
			router.push({
				name: "home"
			});
		});
	}
});

// 导出路由实例
export default router;